<script setup lang="ts">
import { ref, onMounted } from "vue";
import { updateGltf, updateFbx } from "@/utils/gltfLoaders";
import * as mapvgl from "mapvgl";
import { chongqing } from "@/utils/chongqi";
import { center as cscenter, arrCs } from "@/utils/gltfLoaders";
import { convertLL2MC } from "@/utils/mercator/index";
import { FBXLoader } from "bmap-three/examples/jsm/loaders/FBXLoader";
import { GLTFLoader } from "bmap-three/examples/jsm/loaders/GLTFLoader";
import {
  Engine,
  FlyManager,
  UltraDynamicSky,
  EmptySky,
  Default3DTiles,
  DynamicSky,
  AreaMeasure,
  DynamicWeather,
  GeoInstancedMesh,
  StaticSky,
} from "mapv-three";
import {
  PlaneGeometry,
  TextureLoader,
  Mesh,
  MeshLambertMaterial,
  RepeatWrapping,
  SphereGeometry,
  MeshStandardMaterial,
  DoubleSide,
  Color,
  MeshBasicMaterial,
  Scene,
} from "three";
const gltfLoader = new GLTFLoader();
const fbxLoader = new FBXLoader();
const dom = ref();
//const center = [106.560007, 29.566974]; //cscenter;
const center = cscenter;
//const center = [arrCs[0].lon, arrCs[0].lat];
const engines = ref<Engine>();
console.log("--------------------------");
const s = convertLL2MC({
  x: center[0],
  y: center[1],
});
console.log(s);

const loadgtf = () => {
  const glbObj = [
    {
      url: "/bpi/worker/lou1.FBX",

      data: [
        {
          position: [113.012973, 28.116406, 1],
          scale: [1, 1, 1],
        },
      ],
    },
    {
      url: "http://bj.bcebos.com/v1/mapopen/api-demos/model/building5.glb",
      data: [
        {
          position: [113.011697, 28.116784, 0],
          scale: [1, 1, 1],
        },
      ],
    },
  ];

  glbObj.forEach((item) => {
    if (item.url.includes("FBX")) {
      updateFbx(item, engines.value);
    } else {
      updateGltf(item, engines.value);
    }
  });
};

const updateSky = () => {
  // sunny | partlyCloudy | cloudy | overcast | foggy | rainy | snowy
  // 与sky上的属性同义
};
const myDis = ref();

const celiang = () => {
  myDis.value = new BMapGLLib.DistanceTool(map);

  myDis.value.addEventListener("drawend", function (e) {
    console.log("drawend");
    console.log(e.points);
    console.log(e.overlays);
    console.log(e.distance);
  });

  myDis.value.addEventListener("addpoint", function (e) {
    console.log("addpoint");
    console.log(e.point);
    console.log(e.pixel);
    console.log(e.index);
    console.log(e.distance);
  });

  myDis.value.addEventListener("removepolyline", function (e) {
    console.log("removepolyline");
    console.log(e);
  });
};

const zhuanhuan = (lon, lat) => {
  //     坐标常量说明
  // COORDINATES WGS84 = 1，WGS84坐标COORDINATES WGS84 MC = 2，WGS84的平面墨卡托坐标
  // COORDINATES GCJ02 = 3，GCJ02坐标COORDINATES GCJ02 MC = 4，GCJ02的平面墨卡托坐标
  // 大COORDINATES BD09 = 5，百度bd09经纬度坐标
  // COORDINATES BD09 MC = 6，百度bd09墨卡托坐标%，
  //  COORDINATES MAPBAR = 7 mapbar地图坐标
  // COORDINATES 51 = 8，51地图坐标
  // convertor.translate(坐标，坐标类型，需要转换成的坐标类型，转换成功后的回调函数）
  var convertor = new BMapGL.Convertor();
  let points = new BMapGL.Point(lon, lat);
  convertor.translate([points], 5, 6, (data) => {
    console.log(data);
  });
};
const init3Dtitle = () => {
  const tilesetUrl = "/status/json/3dtitle.json";
  const tiles = engines.value?.add(
    new Default3DTiles({
      url: tilesetUrl,
    })
  );

  tiles.rotation.x = Math.PI * 0.5;
  tiles.position = [];
};
onMounted(() => {
  const map = new BMapGL.Map(dom.value);
  zhuanhuan(center[0], center[1]);
  let points = new BMapGL.Point(center[0], center[1]);
  map.centerAndZoom(points, 18);
  map.setMapStyleV2({
    styleId: "0dcb5672684e95119c496d2697ba2577",
  });

  map.enableScrollWheelZoom();
  map.setTilt(90); //地图倾斜角度
  map.setHeading(0); //地图旋转角度

  engines.value = new Engine(map, {
    rendering: {
      enableAnimationLoop: true,
    },
  });

  engines.value.map.setCenter(center);
  engines.value.map.setZoom(18);
  engines.value.map.setPitch(70);
  engines.value.rendering.useMrt = true;
  engines.value.rendering.shadow.enabled = true;
  const sky = engines.value.add(new EmptySky());
  sky.time = 3600 * 14.5;
  // initMaps(map);

  // initPlane();
  // // initMoxings();
  // initMoxing();
  // init3Dtitle();
  init3d();
});

const init3d = () => {
  const tilesetUrl = "/bpi/3dtit/data/tileset.json";
  const tiles = engines.value.add(
    new Default3DTiles({
      url: tilesetUrl,
    })
  );
  tiles.rotation.x = Math.PI * 0.5;
  tiles.position.set(113.011697, 28.116784, 0);
};

const initPlane = () => {
  let textureLoader = new TextureLoader();
  // 加载所需要的纹理图片
  let texture1 = textureLoader.load(
    "https://img2.baidu.com/it/u=3323311628,2330835932&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666"
  );

  let material = new MeshLambertMaterial({
    color: new Color("#000000"),
    side: DoubleSide,
  });
  texture1.wrapS = RepeatWrapping;
  texture1.wrapT = RepeatWrapping;

  // uv两个方向纹理重复数量
  texture1.repeat.set(1, 1);
  const cube = new PlaneGeometry(500, 10, 1);
  const plane = new Mesh(cube, material);
  plane.scale.set(1, 1, 1.0);
  const po = [113.011208, 28.11766];
  const position = engines.value?.map.projectPointArr(po);

  console.log(position);
  plane.position.set(position[0], position[1], 0);
  plane.receiveShadow = true;
  engines.value?.add(plane);
};

const initMoxings = () => {
  gltfLoader.load("http://localhost:984/hours/Parrot.glb", async function (gltf) {
    const model = gltf.scene.children[0];
    console.log(model);
    model.background = new Color("red");

    const ps = [...center, 1];
    const pos = engines.value?.map.projectPointArr(ps);
    model.rotation.x = Math.PI * 0.5;
    model.position.set(...pos);
    const { geometry, material } = model;

    model.traverse(function (child) {
      if (child.isMesh) {
        child.castShadow = true;
        child.receiveShadow = true;
        //  child.rotation.x = Math.PI * 0.1;
        child.position.set(...pos);
      }
    });

    engines.value?.add(model);
  });
};

const initMoxing = () => {
  let textureLoader = new TextureLoader();
  // 加载所需要的纹理图片
  let texture1 = textureLoader.load("http://192.168.40.88:984/image/33.png");
  let material = new MeshLambertMaterial({ map: texture1, side: DoubleSide });
  texture1.wrapS = RepeatWrapping;
  texture1.wrapT = RepeatWrapping;

  fbxLoader.load("/bpi/worker/lou1.FBX", async function (mesh) {
    console.log(mesh);
    mesh.background = new Color("red");
    const model = mesh;
    const ps = [113.013463, 28.116454, 1];
    const pos = engines.value?.map.projectPointArr(ps);
    mesh.rotation.x = Math.PI * 0.5;
    mesh.rotation.y = Math.PI * -0.1;
    mesh.position.set(...pos);

    mesh.traverse(function (child) {
      if (child.isMesh) {
        child.castShadow = true;
        child.receiveShadow = true;
        console.log(child);
        child.material.emissive = child.material.color;
        child.material.emissiveMap = child.material.map;
        //  child.rotation.x = Math.PI * 0.1;

        child.material = material;
      }
    });

    engines.value?.add(mesh);
    // const ps = [...center, 1];
    // const pos = engines.value?.map.projectPointArr(ps);
    // const instance = model.clone();
    // instance.position.set(...pos);
    // // instance.material.emissiveMap = model.material.map;
    // // instance.rotation.y = Math.PI * -0.58;
    // instance.rotation.x = Math.PI * 0.5;
    // //instance.rotation.z = Math.PI * 0.2;
    // //instance.scale.set(..);

    // // engines.value?.add(new GeoInstancedMesh(model.geometry, model.material));
    // // GeoJSONDataSource.fromGeoJSON(randomPoints(center, 0.01, 10000)).then((data) => {
    // //   instancedMesh.dataSource = data;
    // // });
    // instance.traverse((child) => {
    //   console.log(child);
    //   if (child.isMesh) {
    //     child.material.emissiveMap = child.material.map;
    //   }
    // });
  });
};

const initMaps = async (map) => {
  var view = new mapvgl.View({
    map,
  });
  const polygons: any = [];
  chongqing.forEach((item) => {
    const [h, polygon] = item;

    const obj = {
      geometry: {
        type: "Polygon",
        coordinates: [polygon],
      },
      properties: {
        height: h,
      },
    };
    polygons.push(obj);
  });

  var shaperLayer = new mapvgl.ShapeLayer({
    color: "rgba(194, 147, 75, 0.8)", // 柱状图颜色
    enablePicked: true, // 是否可以拾取
    selectedIndex: -1, // 选中项
    selectedColor: "#ee1111", // 选中项颜色
    autoSelect: true, // 根据鼠标位置来自动设置选中项
    opacity: 1,
    // blend: "lighter",
    onClick: (e) => {
      // 点击事件
      console.log(e);
    },
  });
  console.log(polygons);
  view.addLayer(shaperLayer);
  shaperLayer.setData(polygons);
};
</script>

<template>
  <div ref="dom" id="container"></div>
  <input type="button" value="开启" @click="celiang && myDis.open()" />
  <input type="button" value="关闭" @click="myDis.close()" />
</template>

<style lang="scss">
#container {
  width: 100%;
  height: 700px;
}
</style>
